package com.industrial.app.controller;

import cn.hutool.core.date.DateException;
import cn.hutool.core.date.DateUtil;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.industrial.app.domain.BizIndustrialValueAddedByCity;
import com.industrial.app.domain.request.BizIndustrialValueAddedByCityRequest;
import com.industrial.app.service.IBizIndustrialValueAddedByCityService;
import com.industrial.common.core.utils.StringUtils;
import com.industrial.common.core.utils.poi.ExcelUtil;
import com.industrial.common.core.web.controller.BaseController;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.core.web.page.TableDataInfo;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;


/**
 * 分市工业增加值Controller
 *
 * @author SangGuangCan
 * @date 2023-12-27
 */
@RestController
@RequestMapping("/biz/city")
public class BizIndustrialValueAddedByCityController extends BaseController {
    private IBizIndustrialValueAddedByCityService bizIndustrialValueAddedByCityService;

    @Value("${app.file-upload-path}")
    private String fileUploadPath;

    @Autowired
    public BizIndustrialValueAddedByCityController(IBizIndustrialValueAddedByCityService bizIndustrialValueAddedByCityService) {
        this.bizIndustrialValueAddedByCityService = bizIndustrialValueAddedByCityService;
    }

    /**
     * 查询分市工业增加值列表
     */
//    @PreAuthorize("@ss.hasPermi('biz:city:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizIndustrialValueAddedByCity bizIndustrialValueAddedByCity) {
        startPage();
        List<BizIndustrialValueAddedByCity> list = bizIndustrialValueAddedByCityService.selectBizIndustrialValueAddedByCityList(bizIndustrialValueAddedByCity);
        return getDataTable(list);
    }

    /**
     * 导出分市工业增加值列表
     */
//    @PreAuthorize("@ss.hasPermi('biz:city:export')")
//    @Log(title = "分市工业增加值", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizIndustrialValueAddedByCity bizIndustrialValueAddedByCity) {
        List<BizIndustrialValueAddedByCity> list = bizIndustrialValueAddedByCityService.selectBizIndustrialValueAddedByCityList(bizIndustrialValueAddedByCity);
        ExcelUtil<BizIndustrialValueAddedByCity> util = new ExcelUtil<BizIndustrialValueAddedByCity>(BizIndustrialValueAddedByCity.class);
        util.exportExcel(response, list, "分市工业增加值数据");
    }

    /**
     * 获取分市工业增加值详细信息
     */
//    @PreAuthorize("@ss.hasPermi('biz:city:query')")
    @GetMapping(value = "/{baseId}")
    public AjaxResult getInfo(@PathVariable("baseId") String baseId) {
        return success(bizIndustrialValueAddedByCityService.selectBizIndustrialValueAddedByCityByBaseId(baseId));
    }

    /**
     * 新增分市工业增加值
     */
//    @PreAuthorize("@ss.hasPermi('biz:city:add')")
//    @Log(title = "分市工业增加值", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizIndustrialValueAddedByCity bizIndustrialValueAddedByCity) {
        return toAjax(bizIndustrialValueAddedByCityService.insertBizIndustrialValueAddedByCity(bizIndustrialValueAddedByCity));
    }

    /**
     * 修改分市工业增加值
     */
//    @PreAuthorize("@ss.hasPermi('biz:city:edit')")
//    @Log(title = "分市工业增加值", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizIndustrialValueAddedByCity bizIndustrialValueAddedByCity) {
        return toAjax(bizIndustrialValueAddedByCityService.updateBizIndustrialValueAddedByCity(bizIndustrialValueAddedByCity));
    }

    /**
     * 删除分市工业增加值
     */
//    @PreAuthorize("@ss.hasPermi('biz:city:remove')")
//    @Log(title = "分市工业增加值", businessType = BusinessType.DELETE)
    @DeleteMapping("/{baseIds}")
    public AjaxResult remove(@PathVariable String[] baseIds) {
        return toAjax(bizIndustrialValueAddedByCityService.deleteBizIndustrialValueAddedByCityByBaseIds(baseIds));
    }


    /**
     * <p>
     * 查询APP左上角的日期数据
     * </p>
     *
     * @return 日期的集合
     */
//    @Anonymous
    @GetMapping("/getUniqueDatesFromDatabase")
    public AjaxResult getUniqueDatesFromDatabase() {
        List<String> dateArgs = bizIndustrialValueAddedByCityService.getUniqueDatesFromDatabase();
        return AjaxResult.success(dateArgs);
    }

    //    @Anonymous
    @GetMapping("/getIndustrialValueAddedByCityList")
    public AjaxResult getIndustrialValueAddedByCityList(BizIndustrialValueAddedByCityRequest request) {
        if (StringUtils.isBlank(request.getDates())) {
            return AjaxResult.warn("没有获取到指定日期");
        }
        try {
            DateUtil.parse(request.getDates(), "yyyy年MM月");
            return AjaxResult.success(bizIndustrialValueAddedByCityService.getIndustrialValueAddedByCityList(request));
        } catch (DateException de) {
            logger.error("日期格式校验失败,传入日期:{},正确格式:{}", request.getDates(), "yyyy年MM月");
            return AjaxResult.error("日期校验失败");
        } catch (Exception e) {
            logger.error("未知错误:{}", e.getMessage());
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * <p>
     * 将临时表中的数据迁移到正式表虽
     * </p>
     *
     * @return
     */
//    @Anonymous
    @PostMapping("/transferDataInOneClick")
    public AjaxResult transferDataInOneClick() {

        return toAjax(bizIndustrialValueAddedByCityService.transferDataInOneClick());
    }

    /**
     * <p>
     * 清空分市工业增加值数据
     * </p>
     *
     * @return
     */
    @DeleteMapping("/clearAllTableData")
    public AjaxResult clearAllTableData() {
        bizIndustrialValueAddedByCityService.clearAllTableData();
        return AjaxResult.success();
    }

    /**
     * <p>
     * 导入分市工业增加值数据
     * </p>
     *
     * @param params        前端传来的参数，目前只有一个月份
     * @param multipartFile 上传的Excel文件
     * @return 导入是否成功
     */
    @PostMapping("/importExcel")
    public AjaxResult importExcel(@RequestParam Map<String, String> params, @RequestPart("file") MultipartFile multipartFile) {
        try {
            String yearMonth = params.get("yearMonth");
            if (org.apache.commons.lang3.StringUtils.isBlank(yearMonth)) {
                return AjaxResult.warn("请选择导入的年月");
            }
            List<BizIndustrialValueAddedByCity> list = bizIndustrialValueAddedByCityService.selectBizIndustrialValueAddedByCityListNoParams();
            if (list != null && !list.isEmpty()) {
                return AjaxResult.warn("导入前请先清空数据");
            }
            /* 上传文件的路径 */
            String absoluteExcelPath = fileUploadPath + File.separator + IdUtil.simpleUUID() + ".xlsx";
            File file = new File(absoluteExcelPath);
            if (!file.exists()) {
                FileUtil.touch(file);
            }
            multipartFile.transferTo(file);
//            String uploadPath = FileUploadUtils.upload(AppConfig.getProfile(),multipartFile);
//            String absoluteExcelPath = FileUploadUtils.replaceAbsolutePath(uploadPath);
            return bizIndustrialValueAddedByCityService.importExcel(absoluteExcelPath, yearMonth);
        } catch (IOException e) {
            return AjaxResult.error("导入失败");
        }
    }
}
